package com.ruoyi.mysystem.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.mysystem.domain.AdDetails;
import com.ruoyi.mysystem.domain.SysOrder;
import com.ruoyi.mysystem.mapper.SysOrderMapper;
import com.ruoyi.mysystem.service.ISysAdService;
import com.ruoyi.mysystem.util.AliPayUtil;
import com.ruoyi.mysystem.util.MongoDBUtil;
import com.ruoyi.mysystem.util.PaymentConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 广告Controller
 *
 * @author bai
 * @date 2024-01-22
 */
@RestController
@RequestMapping("/mysystem/ad")
public class SysAdController extends BaseController {
    @Autowired
    private ISysAdService sysAdService;

    @Autowired
    private AliPayUtil aliPayUtil;

    @Autowired
    private RedisCache redisCache;

//    @Autowired
//    private MongoDBUtil mongoDBUtil;

    @Autowired
    private  MongoTemplate mongoTemplate;

    @Autowired
    private SysOrderMapper sysOrderMapper;

    private Long orderNum;

    /**
     * 查询分类列表
     */
    @GetMapping("/alipay")
    public AjaxResult alipay(Double money,
                             String textContent,
                             String frontCover,
                             Long expireDate,
                             String username
    ) throws AlipayApiException {
        HashMap data = sysAdService.getAlipayView(
                money,
                textContent,
                frontCover,
                expireDate,
                username
        );
        orderNum = (Long) data.get("orderNum");
        String res = (String) data.get("res");
        return success(res);
    }
    /**
     * 查询分类列表
     */
    @GetMapping("/getAdDetailsList")
    public AjaxResult getAdDetailsList(){
        List<AdDetails> all = mongoTemplate.findAll(AdDetails.class);
        return success(all);
    }
//    @GetMapping("/alipay")
//    public void alipay(Double money,HttpServletResponse response) throws AlipayApiException, IOException {
//        response.setContentType("text/html;charset=utf-8");
//        PrintWriter writer = response.getWriter();
//                writer.write("<!DOCTYPE html>\n" +
//                        "<html lang=\"en\">\n" +
//                        "<head>\n" +
//                        "  <meta charset=\"UTF-8\"/>\n" +
//                        "  <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"/>\n" +
//                        "  <title>Document</title>\n" +
//                        "</head>\n" +
//                        "<body>\n" +
//                                sysAdService.getAlipayView(money)+
//                        "</body>\n" +
//                        "</html>");
//    }

    /**
     * 支付宝支付成功异步回调接口
     *
     * @param request
     * @param response
     * @throws AlipayApiException
     */
    @PostMapping("/alipay/backcall")
    public String alipayBackcall(
            HttpServletRequest request,
            HttpServletResponse response)
            throws AlipayApiException, IOException {
        Map<String, String[]> params = request.getParameterMap();
        Map<String, String> map = new HashMap<>();
        for (String s : params.keySet()) {
            map.put(s, params.get(s)[0]);
        }
        //进行验签
        boolean signVerified = AlipaySignature.rsaCheckV1(
                map,
                PaymentConstants.ALIPAY_PUBLIC_KEY,
                PaymentConstants.CHARSET,
                PaymentConstants.SIGN_TYPE);//调用SDK验证签名
        if (signVerified) {
            // TODO 验证成功
            //先进行查询订单，防止有人篡改通知信息
            AlipayTradeQueryResponse queryResponse = aliPayUtil.query(
                    map.get("out_trade_no"));
            //对比订单金额
            if (!queryResponse.getTotalAmount().equals(
                    map.get("total_amount"))) {
                return "failure";
            }
            //对比订单状态
            if (queryResponse.getTradeStatus().equals("TRADE_SUCCESS")) {
                //如果成功，则更新订单状态，执行发布操作
                String textContent = redisCache.getCacheObject(
                        "adDetails_" + queryResponse.getOutTradeNo());
                String frontCover = redisCache.getCacheObject(
                        "adFrontCover_" + queryResponse.getOutTradeNo());
                Long expireDate = redisCache.getCacheObject(
                        "adExpireDate_" + queryResponse.getOutTradeNo());
                AdDetails adDetails = new AdDetails();
                adDetails.setTextContent(textContent);
                adDetails.setFrontCover(frontCover);
                Date date = new Date();
                long dateNum = date.getTime() + expireDate * 24 * 60 * 60 * 1000;
                adDetails.setExpireAt(new Date(dateNum));
//                MongoDBUtil.saveOne("ad_details", adDetails.getClass());
                mongoTemplate.save(adDetails);
                //将订单状态改为已完成
                SysOrder sysOrder = new SysOrder();
                sysOrder.setOrderNum(orderNum);
                sysOrder.setOrderStatus("1");
                sysOrder.setTradeNum(map.get("trade_no"));
                sysOrderMapper.updateSysOrder(sysOrder);
                System.out.println("支付成功");
            }
            else {
                //如果失败，则更新订单状态
                System.out.println("订单状态：失败");
            }
            //返回“success”代表该条通知处理完成
            return "success";
        }
        else {
            // TODO 验证失败
            System.out.println("异步失败！");
            return "failure";
        }
    }
}
